let categoryId = getParams("categoryId");

// $("#categoryId").attr('value',categoryId);
function appendParam(oldUrl) {
    if (!com.isNull(categoryId)) {
        oldUrl = oldUrl + "?categoryId=" + categoryId;
    }
    return oldUrl;
}

$(function () {
    let colModel = [
        {label: '主键', name: 'id', index: 'id', width: 50, key: true},
        {label: '名字', name: 'name', index: 'name', width: 80}
        , {label: '分类id', name: 'categoryId', index: 'category_id', width: 80}
        , {label: '排序', name: 'orderNum', index: 'order_num', width: 80}
    ];
    if (categoryId != null) {
        vm.getAttributes(categoryId);
        vm.attributes.forEach(function (item) {
            let isShow = item.isShow == 0;
            let model = {label: item.name, name: item.id, hidden: isShow, width: 80,sortable:false};
            // 处理图片
            if (item.type == 5){
                model.formatter = function (cellvalue, options, rowObject) {
                    if (cellvalue) {
                        return '<img src="' + cellvalue + '" class="img-circle" style="width: 80px;height: 80px;" onclick="vm.openFileUrl(\''+cellvalue+'\')"/>';
                    }
                    return "无"
                }
            }
            // 处理视频
            if (item.type == 6){
                model.formatter = function (cellvalue, options, rowObject) {
                    if (cellvalue) {
                        return '<video src="' + cellvalue + '" style="width: 80px;height: 80px;"  onclick="vm.openFileUrl(\''+cellvalue+'\')"/>';
                    }
                    return '无';
                }
            }
            colModel.push(model);
        })
    }
    colModel.push({label: '备注信息', name: 'remark', index: 'remark', width: 80});
    let listUrl = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + 'diy/baseinfo/list';
    listUrl = appendParam(listUrl);
    $("#jqGrid").jqGrid({
        url: listUrl,
        datatype: "json",
        colModel: colModel,
        viewrecords: true,
        height: "100%",
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
});

var vm = new Vue({
    el: '#myapp',
    data: {
        showList: true,
        title: null,
        params: {
            name: null,
            remark: null,
            attributeId: null,
            value: null
        },
        baseInfo: {
            attributes: []
        },
        attributes: []
    },
    computed: {
        allAttributes: function () {
            let allAttributes = [];
            if (com.isNull(this.baseInfo.attributes)) {
                return this.attributes;
            }
            this.attributes.forEach(item => {
                let attribute = this.baseInfo.attributes.find(attr => item.id == attr.id);
                if (com.isNull(attribute)) {
                    attribute = item;
                }
                allAttributes.push(attribute);
            })
            console.log("allAttributes",allAttributes)
            return allAttributes;
        }
    },
    methods: {
        query: function () {
            //初始化查询分页为1，默认从第一页查
            $("#jqGrid").jqGrid('setGridParam',{
                //添加查询条件
                postData:{

                },
                page:1
            });
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";

            vm.baseInfo = {
                categoryId: categoryId
            };
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {

            let msg = vm.validateAttributes();
            if (!com.isNull(msg)) {
                warning(msg);
                return;
            }
            var url = vm.baseInfo.id == null ? "diy/baseinfo/save" : "diy/baseinfo/update";
            vm.baseInfo.attributes = vm.allAttributes;
            //请求参数
            var param = JSON.stringify(vm.baseInfo);

            com.AjaxPost((window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + url, param, "json", function (r) {
                if (r.success) {
                    toast('操作成功');
                    vm.reload();
                } else {
                    warning(r.msg);
                }
            });
        },
        validateAttributes: function (event) {
            let msg = [];
            let requiredMsg = "{ATTR}，必填！";
            let error = null;
            for (let index in vm.allAttributes) {
                error = null;
                let item = vm.allAttributes[index];
                //日期用的layui，不能呢给使用vue赋值，此处要用jQuery来取值
                if (item.type == 2) {
                    item.defaultValue = $('.date1').val();
                }
                if (item.isMust != 1) {
                    continue;
                }
                // 校验是否必填
                if (com.isNull(item.defaultValue)) {
                    error = requiredMsg.replace("{ATTR}", item.name);
                    msg.push(error);
                }
                // 校验是否是数字
                if (item.type == 1) {
                    if (com.isNull(item.defaultValue) || isNaN(item.defaultValue)) {
                        error = item.help+",数字";
                        msg.push(error);
                    }
                    // 是否日期
                } else if (item.type == 2) {
                    item.defaultValue = $('.date1').val();
                    let r = /^\d{4}\-\d{2}\-\d{2}$/;
                    let data = item.defaultValue;
                    if (!r.test(data)) {
                        error = item.help+",日期";
                        msg.push(error);
                    }
                }
            }
            error = "";
            for (let index in msg) {
                let ind = parseInt(index) + 1;
                error += ind + "." + msg[index] + "<br>";//转义字符不生效
            }
            return error;
        },
        del: function (event) {
            ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                var url = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "diy/baseinfo/delete";
                //请求参数
                var param = JSON.stringify(ids);
                com.AjaxPost(url, param, "json", function (r) {
                    if (r.success) {
                        toast('操作成功');
                        vm.reload();
                    } else {
                        warning(r.msg);
                    }
                });
            });
        }, openImportExcel: function (event) {
            openImportExcel();
        },
        importExcel: function (event) {
            var prefix = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "diy/baseinfo";
            // 此种方式，表单post提交，带文件，上传ecxel数据
            $("#diyCategoryId").attr("value", categoryId);
            // 此种方式，下载excel数据模板
            let params = "?diyCategoryId=" + categoryId;
            importExcel(prefix, params, vm);
        },
        exportExcel: function (event) {
            var prefix = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "diy/baseinfo";
            let params = "?diyCategoryId=" + categoryId;
            exportExcel(prefix, params);
        }, exportExcelTemplate: function (event) {
            let prefix = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "diy/baseinfo";
            let params = "?diyCategoryId=" + categoryId;
            exportExcelTemplate(prefix,params);
        },
        getInfo: function (id) {
            var url = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "diy/baseinfo/info/" + id;
            com.AjaxGet(url, null, "json", function (r) {
                vm.baseInfo = r.entity;
            }, null, false)
        },
        getAttributes: function (categoryId) {
            var url = (window.localStorage.getItem("baseURL")?window.localStorage.getItem("baseURL"):"") + "diy/baseinfo/attributes";
            com.AjaxGet(url, {categoryId: categoryId}, "json", function (r) {
                vm.attributes = r.attributes;
            }, null, false)
        }, simpleUploadMyFile: function (attributeIndex) {

            com.simpleUploadMyFile(attributeIndex,vm)
        }, openFileUrl: function (fileUrl) {
            window.open(fileUrl);
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                //添加查询条件
                postData: {
                    name: vm.params.name,
                    remark: vm.params.remark,
                    attributeId: vm.params.attributeId,
                    value: vm.params.value
                },
                page: page
            }).trigger("reloadGrid");
            // 清空文件缓存
            $("input[type=file]").val("");
        },
        reset: function (event) {
                vm.params.name=null
                vm.params.remark=null
                vm.params.attributeId=null
                vm.params.value=null
            vm.reload()
        }

    }
});